package com.ctshk.rpc.payment.factory;

import com.ctshk.rpc.payment.dto.PayDetailsDTO;
import com.ctshk.rpc.payment.dto.rep.alipay.AliPayTradeQueryDTO;
import com.ctshk.rpc.payment.dto.rep.mastercard.QueryTransactionDTO;
import com.ctshk.rpc.payment.dto.rep.unionpay.UnionPayQueryTransDTO;
import com.ctshk.rpc.payment.dto.rep.wechat.QueryOrderInfoDTO;
import com.ctshk.rpc.payment.enums.PayOrderStatus;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @BelongsProject: ctshk-cloud
 * @BelongsPackage: com.ctshk.rpc.payment.utils
 * @Author: hef
 * @CreateTime: 2021-05-06 14:49
 * @Description: 支付详情对象简单工厂
 */
public class PayDetailsDTOSimpleFactory {

    /**
     * 生产对象
     *
     * @param response 阿里返回参数
     * @return
     */
    public static PayDetailsDTO produce(AliPayTradeQueryDTO.ResponseInfo response) {
        PayDetailsDTO dto = new PayDetailsDTO();
        dto.setOrderNumber(response.getOutTradeNo());
        dto.setOrderTime(LocalDateTime.parse(response.getGmtCreate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        dto.setPaymentTime(LocalDateTime.parse(response.getGmtPayment(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        //         * TRADE_FINISHED: 交易已支付。即使发生部分退款或全额退款，或在退款期限到期时，此状态仍然存在。
        //         * WAIT_BUYER_PAY: 交易已创建，正在等待客户付款。
        //         * TRADE_CLOSED: 由于付款超时，交易被关闭
        PayOrderStatus paymentStatus = null;
        switch (response.getTradeStatus()) {
            case "TRADE_FINISHED":
                paymentStatus = PayOrderStatus.FULFIL;
                break;
            case "WAIT_BUYER_PAY":
                paymentStatus = PayOrderStatus.UNPAID;
                break;
            case "TRADE_CLOSED":
                paymentStatus = PayOrderStatus.PAYMENT_ERROR;
                break;
        }
        dto.setPrimaryStatus(response.getTradeStatus());
        dto.setPaymentStatus(paymentStatus);
        dto.setOrderAmount(response.getTotalFee());
//        dto.setUserAccount(response.getBuyerEmail());
        return dto;
    }

    /**
     * 生产对象
     *
     * @param infoDTO 微信响应数据
     * @return
     */
    public static PayDetailsDTO produce(QueryOrderInfoDTO infoDTO) {
        PayDetailsDTO build = PayDetailsDTO.builder()
                .orderNumber(infoDTO.getOSn())
                .orderTime(infoDTO.getCreateTime())
                .paymentTime(infoDTO.getUpdateTime())
                .paymentStatus(Integer.valueOf(1).equals(infoDTO.getIsPay()) ?
                        PayOrderStatus.FULFIL :
                        PayOrderStatus.UNPAID)
                .orderAmount(BigDecimal.valueOf(infoDTO.getPayTotalFee()).divide(BigDecimal.valueOf(100)))
//                .userAccount(infoDTO.getPayUserId())
                .primaryStatus(String.valueOf(infoDTO.getIsPay()))
                .build();
        return build;
    }

    /**
     * 生产对象
     * @param queryTrans 银联支付
     * @return
     */
    public static PayDetailsDTO produce(UnionPayQueryTransDTO queryTrans) {
        if (Objects.isNull(queryTrans)) return null;
        //应答码规范参考open.unionpay.com帮助中心 下载 产品接口规范 《平台接入接口规范-第5部分-附录》
        PayDetailsDTO dto = new PayDetailsDTO();
        dto.setOrderNumber(queryTrans.getOrderId());
        try {
            dto.setOrderTime(LocalDateTime.parse(queryTrans.getTxnTime(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            dto.setPaymentTime(LocalDateTime.parse(queryTrans.getTxnTime(), DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        dto.setOrderAmount(BigDecimal.valueOf(Long.valueOf(queryTrans.getTxnAmt()))
                .divide(BigDecimal.valueOf(100)));
//        dto.setPaymentStatus()
        PayOrderStatus status = PayOrderStatus.UNPAID;
        if (("00").equals(queryTrans.getRespCode())) {//如果查询交易成功
            String origRespCode = queryTrans.getOrigRespCode();
            if (("00").equals(origRespCode)) {
                //交易成功，更新商户订单状态
                status = PayOrderStatus.FULFIL;
            } else if (("03").equals(origRespCode) ||
                    ("04").equals(origRespCode) ||
                    ("05").equals(origRespCode)) {
                //订单处理中或交易状态未明，
                // 需稍后发起交易状态查询交易 【如果最终尚未确定交易是否成功请以对账文件为准】
                status = PayOrderStatus.UNPAID;
            } else {
                //其他应答码为交易失败
                status = PayOrderStatus.PAYMENT_ERROR;
            }
        } else if (("34").equals(queryTrans.getRespCode())) {
            //订单不存在，可认为交易状态未明，需要稍后发起交易状态查询，或依据对账结果为准
            status = PayOrderStatus.UNPAID;
        }
        dto.setPrimaryStatus(queryTrans.getOrigRespCode());
        return dto.setPaymentStatus(status);
    }

    /**
     * 产生对象
     * @param dto MasterCard支付
     * @return
     */
    public static PayDetailsDTO produce(QueryTransactionDTO dto) {
        PayDetailsDTO payDetails = new PayDetailsDTO();
        payDetails.setOrderNumber(dto.getId());
        payDetails.setPrimaryStatus(dto.getStatus());
        payDetails.setOrderTime(dto.getCreationTime());
        payDetails.setPaymentTime(dto.getCreationTime());
        PayOrderStatus paymentStatus = "CAPTURED".equals(dto.getStatus())
                ? PayOrderStatus.FULFIL : PayOrderStatus.UNPAID;
        payDetails.setPaymentStatus(paymentStatus);
        payDetails.setOrderAmount(dto.getAmount());
        /*try {
            payDetails.setUserAccount(dto.getSourceOfFunds().getProvided().getCard().getNumber());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }*/
        return payDetails;
    }
}
